import {request} from "../../request/index"
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    isCollect: false,

  },

  // 商品对象
  GoodsInfo: {},
  /**
   * 生命周期函数--监听页面加载 
   */
  onShow: function () {

    let pages =  getCurrentPages();
    let currentPage = pages[pages.length-1]
    let options = currentPage.options

    let {goods_id} = options
    // console.log(goods_id);
    this.getGoodsDetail(goods_id) 
  },

  async getGoodsDetail(goods_id) {
    let goodsObj = await request({url:"/goods/detail", data:{goods_id}})
    this.GoodsInfo = goodsObj
    console.log(this.GoodsInfo);

    let collect = wx.getStorageSync("collect") || []
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id)

    this.setData ({
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price:goodsObj.goods_price,
        goods_introduce:goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics:goodsObj.pics
      },
      isCollect
    })
  },

  //点击轮播图放大预览
  handlePrevewImage(e) {
    // 构建要预览的图片数组
    let urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    // 接受传递过来的图片url
    let current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls,
    });
  },

  //点击加入购物车
  handleCartAdd() {
    //获取缓存中的购物车  数组
   let cart = wx.getStorageSync("cart") || []
    //判断商品是否已经存在于购物车数组中
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id)
    if (index === -1) {
      //不存在 第一次添加
      this.GoodsInfo.num = 1
      this.GoodsInfo.checked = true
      cart.push(this.GoodsInfo)
    } else {
      cart[index].num++
    }

    //重新添加缓存
    wx.setStorageSync("cart", cart);

    wx.showToast({
        title: '加入成功',
        icon: 'success',
        mask: true, //节流
      
      });
  },
  
 async handleCollect() {
    let isCollect = false
    //获取缓存中的收藏数组
    let collect = wx.getStorageSync("collect") || [];
    // 判断该商品是否被收藏
    let index = collect.findIndex(v => v.goods_id === this.GoodsInfo.goods_id)
    //当index !=-1 表示已经收藏过
    if (index != -1) {
      collect.splice(index,1) //取消收藏
      isCollect = false
     await wx.showToast({
        title: '已取消',
        icon: 'none',
        mask: true,
        duration:800
      });
    } else {
      collect.push(this.GoodsInfo)
      isCollect = true
     await wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true,
        duration:800
      });
  
    }
    //存入缓存
    wx.setStorageSync("collect",collect)
    //修改data数据
    this.setData({
      isCollect 
    })
  },

  handlePay() {
    wx.showToast({
      title: '理性消费啊亲',
      icon: 'none',
      image: '',
      duration: 1500,
      mask: true,

    });
  }
})

